#ifndef OSGCLASS_H
#define OSGCLASS_H


#include "common.h"

inline osg::ref_ptr<osg::Geode> createBoxes(osg::ref_ptr<osg::Vec3Array> va)
{
    osg::ref_ptr<osg::Geode> gnode = new osg::Geode;
    for(auto it=va->begin();it!=va->end();it++)
    {
        gnode->addDrawable(new osg::ShapeDrawable(
                               new osg::Box(*it,0.02,0.02,0.02)));
    }
    return gnode.release();
}




class NV : public osg::NodeVisitor
{
public:
    NV(): osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
    {
    }

    void apply(osg::Geode &node)
    {
        //if(node.getName() == "glider")
        //{
            qDebug()<<node.getNumDrawables();

            for(unsigned int i=0;i<node.getNumDrawables();i++)
            {
                osg::ref_ptr<osg::Geometry> gm = dynamic_cast<osg::Geometry*>(node.getDrawable(i));
                osg::ref_ptr<osg::Vec3Array> va = dynamic_cast<osg::Vec3Array*>(gm->getVertexArray());

 /*               group->addChild(createBoxes(va));

                QFile data("D:/output.txt");
                if (data.open(QFile::WriteOnly | QFile::Truncate))
                {
                    QTextStream out(&data);
                    for(auto it = va->begin();it!=va->end();it++)
                    {
                        out<<it->z()<<'\n';
                    }

                }*/
                /*osg::ref_ptr<osg::Vec4Array> ca = dynamic_cast<osg::Vec4Array*>(gm->getColorArray());

                qDebug()<<va->size();
                for(auto it = va->begin();it!=va->end();it++)
                {
                    qDebug()<<"X:"<<it->x()<<"Y:"<<it->y()<<"Z:"<<it->z();
                }
                qDebug()<<ca->size();
                for(auto it = ca->begin();it!=ca->end();it++)
                {
                    qDebug()<<it->r()<<it->g()<<it->b();
                }*/

            }
        //}
        traverse(node);
    }


private:
    osg::ref_ptr<osg::Vec2Array> texture;
};




class osgWidget : public QWidget, public osgViewer::CompositeViewer
{
public:
    osgWidget(): QWidget()
    {
        initViewerCamera();
        setViewerData();
        setViewerLayout();
        setTimer();
    }
    virtual void paintEvent( QPaintEvent* event )
    { frame(); }



protected:
    void initViewerCamera()
    {
        setThreadingModel(osgViewer::CompositeViewer::SingleThreaded);
        // disable the default setting of viewer.done() by pressing Escape.
        setKeyEventSetsDone(0);
        osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
        traits->windowName = "";
        traits->windowDecoration = false;
        traits->x = 0;
        traits->y = 0;
        traits->width = 800;
        traits->height = 600;
        traits->doubleBuffer = true;
        traits->alpha = ds->getMinimumNumAlphaBits();
        traits->stencil = ds->getMinimumNumStencilBits();
        traits->sampleBuffers = ds->getMultiSamples();
        traits->samples = ds->getNumMultiSamples();
        gw = new osgQt::GraphicsWindowQt(traits.get());
        view = new osgViewer::View;
        addView( view );

        osg::Camera* camera = view->getCamera();
        camera->setGraphicsContext(gw);

        camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );
        camera->setProjectionMatrixAsPerspective(
            30.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 1.0f, 10000.0f );
    }
    void setViewerLayout()
    {
        QGridLayout* grid = new QGridLayout;
        grid->addWidget( gw->getGLWidget(), 0, 0 );
        setLayout( grid );
    }
    void setTimer()
    {
        connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );
        _timer.start( 10 );
    }
    virtual void setViewerData()//后面就在这里添加代码控制绘图
    {

        osg::ref_ptr<osg::Node> node = new osg::ShapeDrawable(
                    new osg::Box(osg::Vec3(0.0,0.0,0.0),10.0));
        //osg::ref_ptr<osg::Node> node2 = osgDB::readNodeFile("D:\\download\\earthResource\\terrain\\pingyang.ive");
        osg::ref_ptr<osg::Node> node2 = osgDB::readNodeFile("glider.osg");

        node2->setName("glider");
        osg::ref_ptr<osg::Group> root = new osg::Group;
        root->addChild(node2);
        view->setSceneData(root);


        NV nv;
        node2->accept(nv);
        //view->setSceneData(gp);




        osg::StateSet* stateset = node2->getOrCreateStateSet();
        osg::Program* program = new osg::Program;
        stateset->setAttribute(program);

        // get shaders from file
        osg::ref_ptr<osg::Texture2D> baseTex = new osg::Texture2D;
        baseTex->setImage(osgDB::readImageFile("D:\\OpenSceneGraph-Data\\Images\\forestWall.png"));
        baseTex->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
        baseTex->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);


        stateset->setTextureAttributeAndModes(0, baseTex);
        osg::Uniform* baseTextureSampler = new osg::Uniform("baseTex",0);
        stateset->addUniform(baseTextureSampler);

        program->addShader(osg::Shader::readShaderFile(
                               osg::Shader::VERTEX, "D:/oldDocument/QT/osgshader/shader110.vert"));
                               //osg::Shader::VERTEX, "D:/QtProj/osgshader/shader110.vert"));
        program->addShader(osg::Shader::readShaderFile(
                               osg::Shader::FRAGMENT, "D:/oldDocument/QT/osgshader/shader110.frag"));
                               //osg::Shader::FRAGMENT, "D:/QtProj/osgshader/shader110.frag"));
        stateset->setAttributeAndModes(program,osg::StateAttribute::ON);
/*
        osg::Uniform* brickColor = new osg::Uniform("brickColor",osg::Vec3(1.0,0.0,0.0));
        osg::Uniform* motarColor = new osg::Uniform("motarColor",osg::Vec3(0.8,0.8,0.8));
        osg::Uniform* brickSize = new osg::Uniform("brickSize",osg::Vec2(0.1,0.1));
        osg::Uniform* brickPct = new osg::Uniform("brickPct",osg::Vec2(0.8,0.95));
        stateset->addUniform(brickColor);
        stateset->addUniform(motarColor);
        stateset->addUniform(brickSize);
        stateset->addUniform(brickPct);
*/


        view->addEventHandler( new osgGA::StateSetManipulator(
                                   view->getCamera()->getOrCreateStateSet()) );

        view->setCameraManipulator(new osgGA::TrackballManipulator);
    }


protected:
    QTimer _timer;
    osgQt::GraphicsWindowQt* gw;
    osgViewer::View* view;
};




#endif // OSGCLASS_H
